package org.numanint.utils;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.numanint.Activator;
import org.numanint.wizard.WebProjectConfig;

public class UIutils {

	public static ImageDescriptor getImageDescriptor(String path) {
		return AbstractUIPlugin.imageDescriptorFromPlugin(Activator.PLUGIN_ID, path);
	}

	public static void unjar(InputStream is, String targetPath) throws Exception {
		ZipInputStream zis = new ZipInputStream(is);
		ZipEntry entry;
		int BUFFER = 2048;
		while ((entry = zis.getNextEntry()) != null) {			
			String targetFile = targetPath + entry.getName().replace("WebContent",WebProjectConfig.webContent)
			.replace("src", WebProjectConfig.srcDir);
			targetFile = targetFile.replace('/', System.getProperty("file.separator").charAt(0));
			File f = new File(targetFile);
			if(!f.exists()) new File(targetFile.substring(0,targetFile.lastIndexOf( System.getProperty("file.separator")))).mkdirs();
			if(!f.isDirectory()){
				int count;
				byte data[] = new byte[BUFFER];
				FileOutputStream fos = new FileOutputStream(targetFile);
				BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);
				while ((count = zis.read(data, 0, BUFFER)) != -1) {
					dest.write(data, 0, count);
				}
				dest.flush();
				dest.close();
			}
		}

	}
	
	public static void txtFileReplace(String filename,String oldStr,String newStr) throws Exception{
		BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filename),"UTF-8"));
		StringBuffer context = new StringBuffer();
		String data = null;
		while((data = br.readLine())!=null)
		 context.append(data.replaceAll(oldStr,newStr)+System.getProperty("line.separator"));
		br.close();
		PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(filename),"UTF-8"),true);  
		pw.println(context);
		pw.flush();
		pw.close();
	}
	
	public static void main(String[] args){
		try{

		}catch(Exception e){
			e.printStackTrace();
		}
	}
}
